package com.common;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletResponse;

public class FileUtil {

//	@SuppressWarnings("resource")
//	public static void download(String file, HttpServletResponse res) throws IOException {
//        // 发送给客户端的数据
//        OutputStream outputStream = res.getOutputStream();
//        byte[] buff = new byte[1024];
//        BufferedInputStream bis = null;
//        // 读取filename
//        bis = new BufferedInputStream(new FileInputStream(new File(file)));
//        int i = bis.read(buff);
//        while (i != -1) {
//            outputStream.write(buff, 0, buff.length);
//            outputStream.flush();
//            i = bis.read(buff);
//        }
//    }
//	
	
	/**
	 * 下载项目根目录下doc下的文件
	 * @param response response
	 * @param fileName 文件名
	 * @return 返回结果 成功或者文件不存在
	 */
	public static String downloadFile(HttpServletResponse response, String filePath,String fileName) {
		response.setHeader("content-type", "application/octet-stream");
		response.setContentType("application/octet-stream");
		try {
			response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
		} catch (UnsupportedEncodingException e2) {
			e2.printStackTrace();
		}
		byte[] buff = new byte[1024];
		BufferedInputStream bis = null;
		OutputStream os = null;		
		try {
			os = response.getOutputStream();
			bis = new BufferedInputStream(new FileInputStream(new File(filePath)));
			int i = bis.read(buff);
			while (i != -1) {
				os.write(buff, 0, buff.length);
				os.flush();
				i = bis.read(buff);
			}
		} catch (FileNotFoundException e1) {
			return "系统找不到指定的文件";
		}catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return "success";
	}

}
